<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Upload
{
    /**
     * 实例化阿里云oos
     * @return object 实例化得到的对象
     */
    function new_oss()
    {
        vendor('Alioss.autoload');
        $config = config("ALIOSS_CONFIG");
        $oss    = new OssClient($config['KEY_ID'], $config['KEY_SECRET'], $config['END_POINT']);
        return $oss;
    }

    /**
     * 通用上传接口
     * @return \think\response\Json
     */
    public function upload(Request $request)
    {

        foreach ($_FILES as $key => $value) {
            $file_key = $key;
        }

        $config = [
            'size' => 42949672960,
            'ext' => 'jpg,gif,png,bmp,mp3,wav,wma,mp4,avi,wmv,rm,rmvb,mpg,mpeg,3gp,mov,flv,mkv,caf'
        ];

        $res_rules = $request->file($file_key)->check($config);

        if (empty($res_rules)) {
            $result = [
                'error' => 1,
                'message' => '文件验证不通过'
            ];
            return json($result);
        }

        $object_name  = $request->file($file_key)->getInfo('name');//拿到文件名
        $explod_obect = pathinfo($object_name);//拆分
        $ali_new_name = md5($explod_obect['filename']) . '.' . $explod_obect['extension'];//加密
        $date         = date('Y-m-d-H-i', time());//时间

        try {
            // 获取配置项
            $bucket = config('ALIOSS_CONFIG.BUCKET');
            // 实例化oss类
            $oss  = $this->new_oss();
            $path = $request->file($file_key)->getRealPath();
            // 上传到oss
            $oss1 = $oss->uploadFile($bucket, 'uploads/' . $date . '/' . $file_key . '/' . $ali_new_name, $path);
            if ($oss1) {
                $url_return = $oss1['info']['url'];
                $url_return = str_replace('http://', 'https://', $url_return);
                $result     = [
                    'error' => 0,
                    'type' => $file_key,
                    'url' => $url_return
                ];
            } else {
                $result = [
                    'error' => 1,
                    'message' => $request->file($file_key)->getError()
                ];
            }
            return json($result);
        } catch (OssException $e) {
            return json(['error' => 500, 'message' => $e->getMessage()]);
        }
    }
}